package com.kgis.kp.common.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author zhxiaomiao
 * 
 */
public abstract class DateFormatUtil extends Detect {

	private static final transient Log log = LogFactory.getLog(DateFormatUtil.class);

	public static final String DATATIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

	public static final String DATA_FORMAT = "yyyy-MM-dd";

	public static final String RFC3339_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";

	private static ThreadLocal<DateFormat> datetimeFormat = new ThreadLocal<DateFormat>() {
		protected synchronized DateFormat initialValue() {
			return new SimpleDateFormat(DATATIME_FORMAT);
		}
	};

	private static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
		protected synchronized DateFormat initialValue() {
			return new SimpleDateFormat(DATA_FORMAT);
		}
	};

	private static ThreadLocal<DateFormat> rfc3339DateFormat = new ThreadLocal<DateFormat>() {
		protected synchronized DateFormat initialValue() {
			return new SimpleDateFormat(RFC3339_FORMAT);
		}
	};

	private static DateFormat getDatetimeFormat() {
		return (DateFormat) datetimeFormat.get();
	}

	private static DateFormat getDateFormat() {
		return (DateFormat) dateFormat.get();
	}

	private static DateFormat getRfc3339DateFormat() {
		return (DateFormat) rfc3339DateFormat.get();
	}

	public static Date toDatetime(String string) {
		try {
			return getDatetimeFormat().parse(string);
		} catch (ParseException e) {
			if (log.isErrorEnabled()) {
				log.error(string, e);
			}
		}
		return null;
	}

	public static String toDatetimeString(Date date) {
		return getDatetimeFormat().format(date);
	}

	public static Date toDate(String string) {
		try {
			return getDateFormat().parse(string);
		} catch (ParseException e) {
			if (log.isErrorEnabled()) {
				log.error(string, e);
			}
		}
		return null;
	}

	public static boolean isExtDate(String string) {
		try {
			getRfc3339DateFormat().parse(string);
			return true;
		} catch (ParseException e) {
			return false;
		}
	}

	public static Date parseExtDate(String string) {
		try {
			return getRfc3339DateFormat().parse(string);
		} catch (ParseException e) {
			if (log.isErrorEnabled()) {
				log.error(string, e);
			}
		}
		return null;
	}

	public static String toDateString(Date date) {
		return getDateFormat().format(date);
	}

	// 转化UTC时间格式字符串(2007-10-23T17:15:44.000Z)
	public static Date parseUTCDate(String string) {
		string = string.replace("Z", " UTC");
		try {
			return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(string);
		} catch (ParseException e) {
			if (log.isErrorEnabled()) {
				log.error(string, e);
			}
		}
		return null;
	}

}
